import os
import json
import requests


def send_to_feishu(msg):
    # 从环境变量获取飞书Webhook地址（建议使用环境变量配置）
    webhook_url = os.getenv('FEISHU_WEBHOOK_URL', 'https://open.feishu.cn/open-apis/bot/v2/hook/a9b61fa3-b2c9-4887-b248-d27a5bcf3491')
    
    headers = {'Content-Type': 'application/json'}
    payload = {
        "msg_type": "text",
        "content": {
            "text": msg
        }
    }

    try:
        response = requests.post(webhook_url, json=payload, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error sending message to Feishu: {e}")
        raise


def lambda_handler(event, context):
    print("Received event:", json.dumps(event, indent=2))
    
    try:
        # 解析SNS消息
        message = json.loads(event['Records'][0]['Sns']['Message'])
        alarm_name = event['Records'][0]['Sns']['Subject']
        
        # 构造告警信息
        msg = f"""⏰ AWS CloudWatch Alarm 通知:
        
🔔 告警名称: {message['AlarmName']}
📝 描述: {message.get('AlarmDescription', '无描述')}
🔄 状态变化: {message['OldStateValue']} → {message['NewStateValue']}
⏱️ 时间: {event['Records'][0]['Sns']['Timestamp']}
📌 原因: {message['NewStateReason']}"""
        
        print("Formatted message:", msg)
        
        # 发送到飞书
        send_to_feishu(msg)
        
        return {
            'statusCode': 200,
            'body': json.dumps('Notification sent to Feishu successfully!')
        }
        
    except Exception as e:
        print(f"Error processing event: {e}")
        return {
            'statusCode': 500,
            'body': json.dumps('Error processing the notification!')
        }